<template>
<div class="product-main">
    <div class="page-header">
        <h1>品尝美食</h1>
        <p>享受地道乡村特色美食</p>
    </div>
    
    <div class="cards-container">
        <div class="product-card" v-for="(product, index) in tableData" :key="index" @click="showDetail(product, index)">
            <div class="card-image">
                <img :src="product.productPicture" :alt="product.productName" />
            </div>
            <div class="card-content">
                <h3 class="card-title">{{ product.productName }}</h3>
                <div class="card-info">
                    <p class="info-item">
                        <i class="el-icon-shopping-bag-1"></i>
                        {{ product.productDesc.length > 15 ? product.productDesc.substring(0, 15) + '...' : product.productDesc }}
                    </p>
                    <p class="info-item">
                        <i class="el-icon-s-ticket"></i>
                        {{ product.productPrice }}元
                    </p>
                    <div class="rating">
                        <el-rate v-model="product.productStar" disabled show-score text-color="#ff9900" :max="5"></el-rate>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
        title="美食详情"
        :visible.sync="detailVisible"
        width="800px"
        :before-close="handleClose">
        <div class="detail-dialog" v-if="selectedProduct">
            <div class="detail-image">
                <img :src="selectedProduct.productPicture" :alt="selectedProduct.productName" />
            </div>
            <div class="detail-content">
                <h2>{{ selectedProduct.productName }}</h2>
                <div class="detail-info">
                    <p><i class="el-icon-shopping-bag-1"></i> 美食类型：{{ selectedProduct.productType }}</p>
                    <p><i class="el-icon-s-ticket"></i> 单件价格：{{ selectedProduct.productPrice }}元</p>
                    <p><i class="el-icon-s-promotion"></i> 发布时间：{{ selectedProduct.productDate }}</p>
                    <p><i class="el-icon-user"></i> 推荐商家：{{ selectedProduct.productAuthor }}</p>
                    <p><i class="el-icon-star-on"></i> 推荐星级：<el-rate v-model="selectedProduct.productStar" disabled show-score text-color="#ff9900" :max="5"></el-rate></p>
                    <p><i class="el-icon-document"></i> 美食介绍：{{ selectedProduct.productDesc }}</p>
                </div>
                <div class="detail-actions">
                    <el-button type="primary" size="large" @click="handleBook">立即预订</el-button>
                </div>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="detailVisible = false">关 闭</el-button>
        </span>
    </el-dialog>

    <!-- 预订对话框 -->
    <el-dialog
        title="预订美食"
        :visible.sync="dialogVisible"
        width="500px"
        :before-close="handleClose">
        <div class="booking-dialog">
            <el-table :data="bookingInfo" border style="width: 100%; margin-bottom: 20px;">
                <el-table-column prop="name" label="项目" width="120"></el-table-column>
                <el-table-column prop="value" label="内容"></el-table-column>
            </el-table>

            <el-form :model="bookForm" label-width="100px">
                <el-form-item label="预订数量" required>
                    <el-input-number v-model="bookForm.quantity" :min="1" style="width: 100%;"></el-input-number>
                </el-form-item>
                <el-form-item label="预订时间" required>
                    <el-date-picker
                        v-model="bookForm.bookTime"
                        type="datetime"
                        placeholder="选择日期时间"
                        :picker-options="{
                            disabledDate(time) {
                                return time.getTime() < Date.now() - 86400000;
                            }
                        }"
                        style="width: 100%;">
                    </el-date-picker>
                </el-form-item>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmBooking">确 定</el-button>
        </span>
    </el-dialog>
</div>
</template>

<script>
const axios = require('axios')
const qs = require('qs')
const ele = require('element-ui')

export default {
    name: 'product_page',
    data() {
        return {
            productID: '',
            productName: '',
            productDate: '',
            productType: '',
            productPrice: '',
            productDesc: '',
            productAuthor: '',
            productStar: 0,
            productPicture: '',
            tableData: [],
            // 详情相关数据
            detailVisible: false,
            selectedProduct: null,
            // 预订相关数据
            dialogVisible: false,
            bookForm: {
                quantity: 1,
                bookTime: ''
            },
            bookingInfo: []
        }
    },
    methods: {
        detail(index) {
            this.productID = this.tableData[index].productID
            this.productName = this.tableData[index].productName
            this.productDate = this.tableData[index].productDate
            this.productType = this.tableData[index].productType
            this.productPrice = this.tableData[index].productPrice
            this.productPicture = this.tableData[index].productPicture
            this.productAuthor = this.tableData[index].productAuthor
            this.productDesc = this.tableData[index].productDesc
            this.productStar = parseFloat(this.tableData[index].productStar)
        },
        showDetail(product, index) {
            this.selectedProduct = product;
            this.detailVisible = true;
        },
		handleBook() {
            const currentUser = localStorage.getItem("userName");
			if (currentUser === "" || currentUser == null) {
				this.$message.warning('请先登录');
				this.$router.push('/login');
				return;
			}

            // 设置当前选中的美食信息
            if (this.selectedProduct) {
                this.productID = this.selectedProduct.productID;
                this.productName = this.selectedProduct.productName;
                this.productPrice = this.selectedProduct.productPrice;
                this.productType = this.selectedProduct.productType;
                this.productStar = this.selectedProduct.productStar;
            }

            // 准备预订信息
            this.bookingInfo = [
                {
                    name: '美食名称',
                    value: this.productName
                },
                {
                    name: '美食单件价格',
                    value: this.productPrice+"元"
                },
                {
                    name: '美食类型',
                    value: this.productType
                },
                {
                    name: '推荐星级',
                    value: this.productStar,
                    render: (h, params) => {
                        return h('el-rate', {
                            props: {
                                value: params.row.value,
                                disabled: true,
                                'show-score': false,
                                'text-color': '#ff9900'
                            }
                        })
                    }
                }
            ];

            // 重置表单
            this.bookForm = {
                quantity: 1,
                bookTime: new Date()
            };

            // 显示对话框
            this.dialogVisible = true;
        },

        // 确认预订
        confirmBooking() {
            // 表单验证
            if (!this.bookForm.quantity || !this.bookForm.bookTime) {
                this.$message.warning('请填写完整预订信息');
                return;
            }

            this.$confirm('确认预订吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
				let _this = this;
                axios({
                    method: 'post',
                    url: 'http://localhost:8080/buyProduct',
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    },
                    params: {
                        productID: this.productID,
                        num: this.bookForm.quantity,
                        startDate: this.bookForm.bookTime,
                        userName: localStorage.getItem("userName")
                    }
                }).then(function(response) {
					console.log(response.data)
					if(response.data.status === "success"){
						_this.$message.success(response.data.message);
                    	_this.dialogVisible = false;
					}else{
						_this.$message.error(response.data.message);
                    	console.log(error);
					}
                }).catch(function(error) {
                    _this.$message.error('报名失败');
                    console.log(error);
                });
            }).catch(() => {
                // 取消预订，不做处理
            });
        },

        // 关闭对话框
        handleClose(done) {
            this.detailVisible = false;
            this.dialogVisible = false;
            this.selectedProduct = null;
            if (done) done();
        }
    },
    created() {
        let _this = this
        this.userName = window.localStorage.getItem('userName')
        axios({
            method: 'get',
            url: 'http://localhost:8080/getProductList',
            headers: {
                'Content-type': 'application/x-www-form-urlencoded'
            }
        }).then(function (response) {
            _this.tableData = response.data.dataList
            console.log(_this.tableData)
        }).catch(function (error) {
            console.log(error)
        })
    }
};
</script>

<style scoped>
.product-main {
    min-height: 100vh;
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #fecfef 100%);
    padding: 40px 20px;
}

.page-header {
    text-align: center;
    margin-bottom: 40px;
    color: white;
}

.page-header h1 {
    font-size: 2.5rem;
    margin-bottom: 10px;
    font-weight: 700;
}

.page-header p {
    font-size: 1.2rem;
    opacity: 0.9;
}

.cards-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 30px;
    max-width: 1400px;
    margin: 0 auto;
}

.product-card {
    background: white;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    transition: all 0.3s ease;
    cursor: pointer;
}

.product-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

.card-image {
    position: relative;
    height: 250px;
    overflow: hidden;
}

.card-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
}

.product-card:hover .card-image img {
    transform: scale(1.05);
}

.card-content {
    padding: 15px;
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.card-title {
    font-size: 1.2rem;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
    line-height: 1.3;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

.card-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.info-item {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 0.85rem;
    margin: 0;
}

.info-item i {
    color: #42b983;
    margin-right: 6px;
    width: 14px;
}

.rating {
    margin-top: 5px;
}

/* 详情对话框样式 */
.detail-dialog {
    display: flex;
    gap: 20px;
}

.detail-image {
    flex: 1;
}

.detail-image img {
    width: 100%;
    height: 300px;
    object-fit: cover;
    border-radius: 8px;
}

.detail-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.detail-content h2 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 1.8rem;
    font-weight: 600;
}

.detail-info p {
    margin: 12px 0;
    color: #666;
    line-height: 1.6;
    display: flex;
    align-items: flex-start;
}

.detail-info i {
    color: #42b983;
    margin-right: 8px;
    width: 16px;
    margin-top: 2px;
}

.detail-actions {
    margin-top: 20px;
    text-align: center;
}

/* 预订对话框样式 */
.booking-dialog .el-input-number {
    width: 100%;
}

.booking-dialog .el-form-item {
    margin-bottom: 20px;
}

.custom-dialog .el-dialog__body {
    padding: 20px 30px;
}

.el-dialog {
    border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .cards-container {
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 20px;
    }
    
    .page-header h1 {
        font-size: 2rem;
    }
    
    .page-header p {
        font-size: 1rem;
    }
}

@media (max-width: 480px) {
    .cards-container {
        grid-template-columns: 1fr;
    }
    
    .product-main {
        padding: 20px 10px;
    }
}
</style>
